/*****************************************************************
 *
 *@filename DBExcelMapper.java
 *@author EverWang
 *@date 2013-9-26
 *@copyright (c) 2012-2022  wyyft@163.com All rights reserved.
 *
 *****************************************************************/
package com.featherlike.feather.generator.excel;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import jxl.Sheet;
import jxl.Workbook;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.featherlike.feather.generator.entity.Column;
import com.featherlike.feather.generator.entity.Table;
import com.featherlike.framework.common.util.StringUtil;

/**
 * jxl实现的数据库Excel读取，转换成tableMap
 * 
 * @author EverWang
 * @Description
 */
public class ExcelMapperJXL implements ExcelMapper {
	private static Logger logger = LoggerFactory
			.getLogger(ExcelMapperJXL.class);

	public Map<Table, List<Column>> createTableMap(String inputPath) {
		Map<Table, List<Column>> tableMap = new LinkedHashMap<Table, List<Column>>();
		try {
			File file = new File(inputPath);
			Workbook workbook = Workbook.getWorkbook(file);
			String moduleName = workbook.getSheet(0).getName().toLowerCase();
			for (int i = 1; i < workbook.getNumberOfSheets(); i++) {
				Sheet sheet = workbook.getSheet(i);
				String tableName = moduleName + '_'
						+ sheet.getName().toLowerCase();
				String tablePK = "";
				List<Column> columnList = new ArrayList<Column>();
				for (int row = 1; row < sheet.getRows(); row++) {
					String name = sheet.getCell(0, row).getContents().trim();
					String type = sheet.getCell(1, row).getContents().trim();
					String length = sheet.getCell(2, row).getContents().trim();
					String precision = sheet.getCell(3, row).getContents()
							.trim();
					String notnull = sheet.getCell(4, row).getContents().trim();
					String pk = sheet.getCell(5, row).getContents().trim();
					String comment = sheet.getCell(6, row).getContents().trim();
					String listPage = sheet.getCell(7, row).getContents()
							.trim();
					String queryPage = sheet.getCell(8, row).getContents()
							.trim();
					String modifyPage = sheet.getCell(9, row).getContents()
							.trim();
					String asLink = sheet.getCell(10, row).getContents().trim();
					String dictType = sheet.getCell(11, row).getContents()
							.trim();
					columnList.add(new Column(name, type, length, precision,
							notnull, pk, comment, listPage, queryPage,
							modifyPage, asLink, dictType));
					if (StringUtil.isNotEmpty(pk)) {
						tablePK = name;
					}
				}
				tableMap.put(new Table(tableName, tablePK), columnList);
			}
			workbook.close();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new RuntimeException(e.getMessage(), e);
		}
		return tableMap;
	}

}
